<?php

namespace App\Jobs;

use App\Models\YaoDivination;
use App\Models\Divination;
use App\Models\DivinationAiRecord;
use App\Models\DivinationCategoriesRelation;
use App\Models\Category;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use OpenAI;
use Rainsens\Dinglog\Facades\Dinglog;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;

class MakeDeepContentJob implements ShouldQueue
{
	use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

	public int $divinationId;
	public int $byDivinationId;
	public int $categoryId;


	public function __construct($divinationId,$byDivinationId,$categoryId)
	{
		$this->divinationId = $divinationId;
		$this->byDivinationId = $byDivinationId;
		$this->categoryId = $categoryId;
	}
	
	public function handle()
   	{
   		$category = Category::find($this->categoryId);
   		if($category->prompt){
   			$divination = Divination::find($this->divinationId);
   			$byDivination = Divination::find($this->byDivinationId);
   			$yaoNum = YaoDivination::query()->where("divination_id",$this->divinationId)->where("by_dividend_id",$this->byDivinationId)->first();

   			DivinationAiRecord::where('by_dividend_id', $this->byDivinationId)->where("dividend_id",$this->divinationId)->where("category_id",$this->categoryId)->delete();
   			$content = "";
   			if($yaoNum){
   				
   				$yaoString = config('site.bianyao')[$yaoNum->yao_count];
   				$aiQdString  = "【本卦".$divination->title." ".$yaoString." ".$byDivination->title."】";
   				$prompt = str_replace("【本卦】",$aiQdString,$category->prompt);
   				
   				$lastContent = $this->chats(0,$prompt,$content);

   				$relation = DivinationCategoriesRelation::query()->where("yao_divination_id",$yaoNum->id)->where("category_id",$this->categoryId)->first();
   				if($relation){

   					$relation->update(["content"=>$lastContent]);
   				}else{

   					$insertArr = [
   						'yao_divination_id'=>$yaoNum->id,
   						'category_id'=>$this->categoryId,
   						'content'=>$lastContent
   					];
   					DivinationCategoriesRelation::insert($insertArr);
   				}
   				
   			}
   		}
    	
   	}

        public function chats($chatId,$prompt,$content){

         $model="gpt-4o";
         $first = 0;
         $messages = [];
         //if($chatId){
              $records = DivinationAiRecord::query()->where("by_dividend_id",$this->byDivinationId)->where("dividend_id",$this->divinationId)->where("category_id",$this->categoryId)->get();

              foreach($records as $k=>$v){

                  $messages[$k]['role'] = $v->role;
                  $messages[$k]['content'] = $v->content;
              }

         //}

         if(!$messages){

            $messages = [
                  ['role' => 'system', 'content' => $prompt],
            ];

            $first = 1;
         }
       
         $titleContent = [
               'model' => $model,
               'messages' => $messages,
               'temperature'=>"0.7"
         ]; 

         $titleResult = $this->curl($titleContent);
         
         $titleResult = json_decode($titleResult,true);


         if(isset($titleResult['choices'])){

           
            if(strstr($titleResult['choices'][0]['message']['content'],'继续')){

               $lastInsertArr = [];
               if($first ==1){
                  foreach($messages as $k=>$v){
                     $arr = [
                     	'by_dividend_id'=>$this->byDivinationId,
                     	'dividend_id'=>$this->divinationId,
                     	'category_id'=>$this->categoryId,
                        'chat_id'=>$titleResult['id'],
                        'content'=> $v['content'],
                        'role'=>$v['role'],
                     ];
                     array_push($lastInsertArr,$arr);

                  }

               }
               $insertZlArr = [
               	  'by_dividend_id'=>$this->byDivinationId,
             	  'dividend_id'=>$this->divinationId,
             	  'category_id'=>$this->categoryId,
                  'chat_id'=>$titleResult['id'],
                  'content'=> $titleResult['choices'][0]['message']['content'],
                  'role'=>'assistant'
               ];

               array_push($lastInsertArr,$insertZlArr);



               $jxArr = [
               	  'by_dividend_id'=>$this->byDivinationId,
             	  'dividend_id'=>$this->divinationId,
             	  'category_id'=>$this->categoryId,
                  'chat_id'=>$titleResult['id'],
                  'content'=> '继续',
                  'role'=>'user'
               ];


               array_push($lastInsertArr,$jxArr);
               DivinationAiRecord::insert($lastInsertArr);

               $content = $content .  str_replace("继续","",$titleResult['choices'][0]['message']['content']);
               $content = $this->chats($titleResult['id'],$prompt,$content);


               
            }else{
                $insertZlArr = [
                  'by_dividend_id'=>$this->byDivinationId,
             	  'dividend_id'=>$this->divinationId,
             	  'category_id'=>$this->categoryId,
                  'chat_id'=>$titleResult['id'],
                  'content'=> $titleResult['choices'][0]['message']['content'],
                  'role'=>'assistant'
               ];

                DivinationAiRecord::insert($insertZlArr);

                $content = $content . $titleResult['choices'][0]['message']['content'];
            }
             
             return  $content;
             /* return  $titleResult['choices'][0]['message']['content'];*/

         }else{

            return false;
         }
    }


    public function curl($data){

      $curl = curl_init();
      $data = json_encode($data);


      curl_setopt_array($curl, array(
         CURLOPT_URL => 'https://api.chatanywhere.tech/v1/chat/completions',
         CURLOPT_RETURNTRANSFER => true,
         CURLOPT_ENCODING => '',
         CURLOPT_MAXREDIRS => 10,
         CURLOPT_TIMEOUT => 0,
         CURLOPT_FOLLOWLOCATION => true,
         CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
         CURLOPT_CUSTOMREQUEST => 'POST',
         CURLOPT_POSTFIELDS =>$data,
         CURLOPT_HTTPHEADER => array(
            'Authorization: Bearer '.env('CHATGPT_API_KEY'),
            'User-Agent: Apifox/1.0.0 (https://apifox.com)',
            'Content-Type: application/json'
         ),
      ));

      $response = curl_exec($curl);

      
      return $response;
   }
}
